package com.wbp.cms.web.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.wbp.cms.client.user.domain.UserDO;
import com.wbp.cms.web.util.SessionUtil;


/**
 * @Description:
 * @Department:
 * @author andy.lhc
 * @date 2016年3月11日 上午9:44:51
 */
public class HandlerInterceptorAdapter implements HandlerInterceptor {

  private static final Logger logger =Logger.getLogger(HandlerInterceptorAdapter.class) ;
  private List<String> excludedUrls;

  public void setExcludedUrls(List<String> excludedUrls) {
    this.excludedUrls = excludedUrls;
  }
  
  private List<String>  staticSuffix ; 
  public void setStaticSuffix(List<String> staticSuffix) {
  this.staticSuffix = staticSuffix;
}
  
  private static final  String  loginUrl = "/console/login" ;
  private static final  String  mainUrl  = "/console/main";

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    logger.info("---preHandle---requestUrl: "+ request.getRequestURI());
    String path = request.getServletPath();
    String requestUri = request.getRequestURI();
   // System.out.println("path: " + path+",requestUri: " + requestUri);
    for (String url : excludedUrls) {
       if (requestUri.endsWith(url) ) {
          if(   requestUri.endsWith(loginUrl)  && SessionUtil.getCurrentUser(request.getSession()) !=null)  // 已loing，但又跳到login时，跳到main主页面
              response.sendRedirect(request.getContextPath() +mainUrl);
          else
              return true;
      }
      /*if(path.matches(url)) 
        return true ;*/
    }
    
    for(String suffix:staticSuffix){
       if( requestUri.endsWith(suffix) )   // 过滤 静态后缀文件
          return true ;
    }

    UserDO currentUser = SessionUtil.getCurrentUser(request.getSession());
    if (currentUser == null) {
        response.sendRedirect(request.getContextPath() +loginUrl);
    } else if(requestUri.endsWith("/")){
        requestUri = requestUri.substring(0, requestUri.length()-1) ;
        response.sendRedirect(requestUri);
    }else 
    {
      return true;
    } 
    
    return false;
  }


  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {
  //  logger.info("---postHandle---requestUrl: "+request.getRequestURI());

  }


  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) throws Exception {
//    logger.info("---afterCompletion---requestUrl: "+request.getRequestURI());

  }

}
